<template>
  <div class="app-container">
    <div class="filter-container" style="float:right;">

      <el-button class="filter-item" type="primary" @click="addDeviceDialogVisible=true"> 添加设备 </el-button>
      <el-button class="filter-item" type="primary" @click="addCountDialogVisible=true"> 添加计算 </el-button>
      <el-button class="filter-item" type="primary" @click="excelAddDeviceVisiable=true"> Excel批量导入设备 </el-button>
      <el-button class="filter-item" :loading="downloadLoading" type="primary" icon="el-icon-document" @click="handleDownload"> 导出Excel保存 </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="deviceListLoading"
      :data="deviceList"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      :default-sort="{prop: 'id', order: 'ascending'}"
    >
      <el-table-column label="id" type="index" align="center" />
      <el-table-column label="图标" width="150px" align="center" prop="model">
        <template slot-scope="{row}">
          <svg-icon v-if="row.tag=='infrared'" icon-class="peoples" style="font-size:50px;color:#1296db;" />
          <svg-icon v-if="row.tag=='door'" icon-class="door" style="font-size:50px;color:#1296db;" />
          <svg-icon v-if="row.tag=='switch'" icon-class="switch" style="font-size:50px;color:#1296db;" />
          <svg-icon v-if="row.tag=='axis'" icon-class="axis" style="font-size:50px;color:#1296db;" />
          <svg-icon v-if="row.tag=='circle'" icon-class="circle" style="font-size:50px;color:#1296db;" />
          <svg-icon v-if="row.tag=='control'" icon-class="control" style="font-size:50px;color:#1296db;" />
          <svg-icon v-if="row.tag=='radio'" icon-class="control" style="font-size:50px;color:#1296db;" />
          <svg-icon v-if="row.tag=='count_x'" icon-class="radio" style="font-size:50px;color:#1296db;" />
          <svg-icon v-if="row.tag=='count_gamma'" icon-class="radio" style="font-size:50px;color:#1296db;" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="状态" align="center" prop="online">
        <template slot-scope="{row}">
          <el-tag :type="row.online | onlineTypeFilter">{{ row.online | onlineFilter }}</el-tag>
        </template>
      </el-table-column> -->
      <el-table-column label="名称" align="center" prop="name">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="位置" align="center" prop="position">
        <template slot-scope="{row}">
          <span>{{ row.position }}</span>
        </template>
      </el-table-column>
      <el-table-column label="SN" align="center" prop="sn">
        <template slot-scope="{row}">
          <span>{{ row.sn }}</span>
        </template>
      </el-table-column>
      <el-table-column label="型号" prop="model">
        <template slot-scope="{row}">
          <span>{{ row.model }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订阅" min-width="100px" prop="model">
        <template slot-scope="{row}">
          <span>{{ row.sub }}</span>
        </template>
      </el-table-column>
      <el-table-column label="推送" min-width="100px" prop="model">
        <template slot-scope="{row}">
          <span>{{ row.pub }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="400" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button size="mini" type="primary" icon="el-icon-setting" @click="toSet(row,$index)"> 设置 </el-button>
          <el-button size="mini" type="success" icon="el-icon-upload" @click="toUpdate(row,$index)"> 升级 </el-button>
          <el-button size="mini" type="default" icon="el-icon-more" @click="toLog(row,$index)"> 记录 </el-button>
          <el-button size="mini" type="danger" icon="el-icon-delete" @click="onDelete(row,$index)"> 删除 </el-button>
          <!-- <el-button size="mini" type="warning" @click="toInfo(row)"> 编辑 </el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      title="添加设备"
      :visible.sync="addDeviceDialogVisible"
      width="20%"
      center
    >
      <div class="add-device">
        <el-row type="flex" class="row-bg"> <el-col :span="12"> <el-button class="filter-item" type="primary" @click="addInfrared"> 红外监控设备 </el-button> </el-col> </el-row>
        <el-row type="flex" class="row-bg"> <el-col :span="12"> <el-button class="filter-item" type="primary" @click="addDoor"> 门禁监控设备 </el-button> </el-col> </el-row>
        <el-row type="flex" class="row-bg"> <el-col :span="12"> <el-button class="filter-item" type="primary" @click="addSwitch"> 源控开关设备 </el-button> </el-col> </el-row>
        <el-row type="flex" class="row-bg"> <el-col :span="12"> <el-button class="filter-item" type="primary" @click="addAxis"> 运动轴设备 </el-button> </el-col> </el-row>
        <el-row type="flex" class="row-bg"> <el-col :span="12"> <el-button class="filter-item" type="primary" @click="addControl"> 安全连锁检测控制设备 </el-button> </el-col> </el-row>
        <el-row type="flex" class="row-bg"> <el-col :span="12"> <el-button class="filter-item" type="primary" @click="addRadio"> 辐射器控制设备 </el-button> </el-col> </el-row>
      </div>
    </el-dialog>

    <el-dialog
      title="添加计算"
      :visible.sync="addCountDialogVisible"
      width="20%"
      center
    >
      <div class="add-device">
        <el-row type="flex" class="row-bg"> <el-col :span="12"> <el-button class="filter-item" type="primary" @click="addCountX"> X射线空气比释动能率计算 </el-button> </el-col> </el-row>
        <el-row type="flex" class="row-bg"> <el-col :span="12"> <el-button class="filter-item" type="primary" @click="addCountGamma"> γ射线空气比释动能率计算 </el-button> </el-col> </el-row>
      </div>
    </el-dialog>

    <el-dialog
      title="批量添加设备"
      :visible.sync="excelAddDeviceVisiable"
      width="70%"
      center
    >
      <el-table
        :data="excelDeviceList"
        border
        fit
        highlight-current-row
        style="width: 100%;"
        :default-sort="{prop: 'id', order: 'ascending'}"
      >
        <el-table-column label="id" type="index" align="center" />
        <el-table-column label="图标" width="150px" align="center" prop="model">
          <template slot-scope="{row}">
            <svg-icon v-if="row.tag=='infrared'" icon-class="peoples" style="font-size:50px;color:#1296db;" />
            <svg-icon v-if="row.tag=='door'" icon-class="door" style="font-size:50px;color:#1296db;" />
            <svg-icon v-if="row.tag=='switch'" icon-class="switch" style="font-size:50px;color:#1296db;" />
            <svg-icon v-if="row.tag=='axis'" icon-class="axis" style="font-size:50px;color:#1296db;" />
            <svg-icon v-if="row.tag=='circle'" icon-class="circle" style="font-size:50px;color:#1296db;" />
            <svg-icon v-if="row.tag=='control'" icon-class="control" style="font-size:50px;color:#1296db;" />
            <svg-icon v-if="row.tag=='radio'" icon-class="control" style="font-size:50px;color:#1296db;" />
          </template>
        </el-table-column>
        <el-table-column label="名称" align="center" prop="name">
          <template slot-scope="{row}">
            <span>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="位置" align="center" prop="position">
          <template slot-scope="{row}">
            <span>{{ row.position }}</span>
          </template>
        </el-table-column>
        <el-table-column label="SN" align="center" prop="sn">
          <template slot-scope="{row}">
            <span>{{ row.sn }}</span>
          </template>
        </el-table-column>
        <el-table-column label="型号" prop="model">
          <template slot-scope="{row}">
            <span>{{ row.model }}</span>
          </template>
        </el-table-column>
        <el-table-column label="订阅" min-width="100px" prop="model">
          <template slot-scope="{row}">
            <span>{{ row.sub }}</span>
          </template>
        </el-table-column>
        <el-table-column label="推送" min-width="100px" prop="model">
          <template slot-scope="{row}">
            <span>{{ row.pub }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="400" class-name="small-padding fixed-width">
          <template slot-scope="{row,$index}">
            <el-button size="mini" type="primary" icon="el-icon-plus" @click="onExcelAdd(row,$index)"> 添加 </el-button>
          </template>
        </el-table-column>
      </el-table>
      <upload-excel-component :on-success="handleSuccessExcel" :before-upload="beforeUploadExcel" />
    </el-dialog>

  </div>
</template>

<script>
import { addDevice, getDevices, deleteDevice } from '@/api/device'
import UploadExcelComponent from '@/components/UploadExcel/index.vue'

export default {
  name: 'Device',
  directives: { },
  components: { UploadExcelComponent },
  filters: {
    typeFilter(status) {
      if (status === 1) {
        return 'success'
      } else {
        return 'danger'
      }
    },
    statusFilter(status) {
      if (status === 1) {
        return '正常'
      } else {
        return '异常'
      }
    },
    onlineTypeFilter(status) {
      if (status === 1) {
        return 'success'
      } else {
        return 'danger'
      }
    },
    onlineFilter(status) {
      if (status === 1) {
        return '在线'
      } else {
        return '离线'
      }
    }
  },
  data() {
    return {
      downloadLoading: false,
      value: true,
      tableKey: 0,
      deviceHeader: [],
      deviceList: [],
      deviceListLoading: true,
      showList: [],
      total: 10,
      listQuery: {
        status: 1
      },
      // 按照型号分类
      filterModel: '',
      models: [],
      formLabelWidth: '100px',

      // excel
      excelDeviceHeader: [],
      excelDeviceList: [],

      excelAddDeviceVisiable: false,
      addDeviceDialogVisible: false,
      addCountDialogVisible: false
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.deviceListLoading = true
      getDevices(this.listQuery).then(response => {
        this.deviceListLoading = false
        var data = response.data
        if (data === null) {
          this.deviceList = []
        } else {
          for (var i = 0; i < data.length; i++) {
            data[i].value = JSON.parse(data[i].value)
          }
          data.sort(function(a, b) {
            return a.id - b.id
          })
          console.log(data)
          this.deviceList = data
        }
      })
    },
    onExcelAdd(row, index) {
      console.log(index)
      console.log(row)
      addDevice(row).then(response => {
        if (response.code === 200) {
          this.$message({
            type: 'success',
            message: response.message
          })
        } else this.$message(response.message)
        this.fetchData()
      })
    },
    onExcelDelete() {
    },
    // 导入excel
    beforeUploadExcel(file) {
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true
      }

      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    handleSuccessExcel({ results, header }) {
      console.log('upload excel header:')
      console.log(header)
      console.log('upload excel data:')
      console.log(results)
      this.excelDeviceHeader = header
      for (var i = 0; i < results.length; i++) {
        results[i].value = JSON.parse(results[i].value)
      }
      this.excelDeviceList = results
    },
    // 导出Excel
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['id', 'name', 'sn', 'pub', 'sub', 'model', 'position', 'status', 'lock', 'online', 'value', 'tag', 'order']
        const filterVal = ['id', 'name', 'sn', 'pub', 'sub', 'model', 'position', 'status', 'lock', 'online', 'value', 'tag', 'order']
        var deviceList = JSON.parse(JSON.stringify(this.deviceList))
        for (var i = 0; i < deviceList.length; i++) {
          deviceList[i].value = JSON.stringify(deviceList[i].value)
        }
        const data = this.formatJson(filterVal, deviceList)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        return v[j]
      }))
    },

    // 添加计算模块
    addCountX() {
      this.$router.push({ path: '/device/count_x/add' })
    },
    addCountGamma() {
      this.$router.push({ path: '/device/count_gamma/add' })
    },

    // 添加设备
    addDoor() {
      this.$router.push({ path: '/device/door/add' })
    },
    addSwitch() {
      this.$router.push({ path: '/device/switch/add' })
    },
    addInfrared() {
      this.$router.push({ path: '/device/infrared/add' })
    },
    addAxis() {
      this.$router.push({ path: '/device/axis/add' })
    },
    addCircle() {
      this.$router.push({ path: '/device/circle/add' })
    },
    addControl() {
      this.$router.push({ path: '/device/control/add' })
    },
    addRadio() {
      this.$router.push({ path: '/device/radio/add' })
    },

    toSet(device) {
      console.log('跳转到设置页面~')
      console.log('/device/' + device.tag + '/set')
      this.$router.push({
        path: '/device/' + device.tag + '/set',
        query: device
      })
    },

    toUpdate(device) {
      console.log('跳转到升级页面~')
      console.log('/device/' + device.tag + '/update')
      this.$router.push({
        path: '/device/' + device.tag + '/update',
        query: device
      })
    },

    toLog(device) {
      this.$router.push({
        path: '/device/' + device.tag + '/log',
        query: device
      })
    },

    toInfo(device) {
      this.$router.push({
        path: '/device/' + device.tag,
        query: device
      })
    },

    onDelete(device) {
      this.$confirm('此操作将永久删除该设备, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteDevice(device.id).then(response => {
          if (response.code === 200) {
            this.$message({
              type: 'success',
              message: response.message
            })
          } else this.$message(response.message)
          this.fetchData()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }

  }
}
</script>

<style lang="scss" scoped>

.el-row {
  margin-bottom: 20px;
  &:last-child {
    margin-bottom: 0;
  }
}
.el-col {
  border-radius: 4px;
}

.text {
  font-size: 14px;
}

.item {
  padding: 18px 0;
}

.add-device {
  display: flex;
  flex-direction: column;
  padding: 10px;
  flex-wrap: nowrap;
  justify-content: center;
  align-items: center;
}

</style>
